package views;

import DAO.*;
import Entity.*;
import util.Result;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

/**
 * @author North
 */

public class AdminiView {

    JFrame jFrame;
    JComboBox<String> jComboBox;
    JButton btninsert;
    JTextField txtsearch;
    JButton btnsearch;
    JTable jTable;
    DefaultTableModel defaultTableModel;
    JScrollPane jScrollPane;
    JButton btnupdate;
    JButton btndelete;
    PanelBg jPanel;
    Result resultissenior = new Result();
    String boxItembtnupdate;

    //状态变量
    boolean isSelectedFlag = false;
    int lastrow = 0;
    boolean isSearch = false;

    //修改背景
    class PanelBg extends JPanel {
        Dimension d;
        Image image;

        PanelBg(Dimension d, Image image) {
            this.d = d;
            this.image = image;
        }

        @Override
        public void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, d.width, d.height, this);
        }
    }

    Dimension fmsize = new Dimension(700, 850);
    ImageIcon imageicon = new ImageIcon(this.getClass().getResource("/erhai7.jpg"));

    AdminiView(Result resultissenior) {
        this.resultissenior.setStatus(resultissenior.getStatus());
        this.resultissenior.setMessage(resultissenior.getMessage());
        jFrame = new JFrame("旅游信息管理系统");
        jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
        jFrame.setSize(570, 720);
        jFrame.setLocationRelativeTo(null);//居中
        jFrame.setResizable(false);
        jPanel = new PanelBg(fmsize, imageicon.getImage());
        jPanel.setBounds(0, 0, 570, 720);
        jPanel.setLayout(null);
        jFrame.getContentPane().add(jPanel);

        setComponent();
        addComponent();
        addMethodtoComponent();
        Result resultinit = new Result();
        resultinit.setStatus("-1");
        refreshjTable(resultinit, "");//初始化表格显示表头


        jFrame.setVisible(true);
    }

    /**
     * 设置组件
     */
    public void setComponent() {
        jComboBox = new JComboBox<>();
        if (resultissenior.getStatus().equals("1")) {//判断是否为高级管理员
            jComboBox.addItem("景区");
            jComboBox.addItem("IC卡");
            jComboBox.addItem("会员");
            jComboBox.addItem("网点");
            jComboBox.addItem("初级管理员");
        } else {
            jComboBox.addItem("景区");
            jComboBox.addItem("IC卡");
            jComboBox.addItem("会员");
        }
        jComboBox.setBounds(20, 40, 90, 40);

        btninsert = new JButton("新增");
        btninsert.setBounds(70, 610, 90, 40);

        txtsearch = new JTextField();
        txtsearch.setBounds(115, 40, 300, 40);
        Font font = new Font("宋体", Font.ITALIC, 15);
        txtsearch.setFont(font);
        txtsearch.setForeground(Color.GRAY);
        txtsearch.setText("请输入id编号或者手机号！");

        btnsearch = new JButton("搜索");
        btnsearch.setBounds(430, 40, 90, 40);

        defaultTableModel = new DefaultTableModel();
        jTable = new JTable(defaultTableModel) {
            //表格不允许被编辑
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        //设置表格的列不允许拖动
        jTable.getTableHeader().setReorderingAllowed(false);
        jTable.setRowHeight(35);//设置行高
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
        jTable.setDefaultRenderer(Object.class, tcr);
        jScrollPane = new JScrollPane(jTable);
        jScrollPane.setBounds(20, 100, 500, 480);

        jScrollPane.getViewport().setBackground(Color.WHITE);

        btnupdate = new JButton("修改");
        btnupdate.setBounds(230, 610, 90, 40);

        btndelete = new JButton("删除");
        btndelete.setBounds(385, 610, 90, 40);
    }

    /**
     * 将组件添加到Jpanel中
     */
    public void addComponent() {
        jPanel.add(jComboBox);
        jPanel.add(btninsert);
        jPanel.add(txtsearch);
        jPanel.add(btnsearch);
        jPanel.add(jScrollPane);
        jPanel.add(btnupdate);
        jPanel.add(btndelete);
    }

    /**
     * 向JPanel中的组件添加监听方法
     */
    public void addMethodtoComponent() {

        txtsearch.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if (txtsearch.getText().trim().equals("请输入id编号或者手机号！")) {
                    Font font = new Font("宋体", Font.PLAIN, 15);
                    txtsearch.setFont(font);
                    txtsearch.setForeground(Color.BLACK);
                    txtsearch.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (txtsearch.getText().trim().equals("")) {
                    Font font = new Font("宋体", Font.ITALIC, 15);
                    txtsearch.setFont(font);
                    txtsearch.setForeground(Color.GRAY);
                    txtsearch.setText("请输入id编号或者手机号！");
                }
            }
        });

        //点击后选中再次点击取消选中
        jTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = 0;
                row = jTable.getSelectedRow();
                if (lastrow == row) {
                    if (isSelectedFlag) {
                        jTable.getSelectionModel().clearSelection();
                    }
                    isSelectedFlag = !isSelectedFlag;
                } else {
                    isSelectedFlag = true;
                }
                lastrow = row;
            }
        });
        btnsearch.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isSearch = true;
                List<String> boxItembtnesearch = getBoxItem();
                boxItembtnupdate = boxItembtnesearch.get(1);
                isSelectedFlag = false;
                InterTabDao interTabDao = new InterTabDao();
                ICcardDao iCcardDao = new ICcardDao();
                MangerDao mangerDao = new MangerDao();
                scTabDao scTabDao = new scTabDao();
                vipTabDao vipTabDao = new vipTabDao();
                Result result;
                List<String> list = new ArrayList<>();
                String str = getBoxItem().get(1);
                String id = txtsearch.getText().trim();
                System.out.println("btnsearch.addActionListener:str->" + str + "id->" + id);
                if (id.equals("请输入id编号或者手机号！")) {
                    id = "";

                    switch (str) {
                        case "景区":
                            result = scTabDao.Querry(id);
                            refreshjTable(result, "景区");
                            break;
                        case "IC卡":
                            result = iCcardDao.Querry(id);
                            refreshjTable(result, "IC卡");
                            break;
                        case "会员":
                            result = vipTabDao.Querry(id);
                            refreshjTable(result, "会员");
                            break;
                        case "网点":
                            result = interTabDao.Querry(id);
                            refreshjTable(result, "网点");
                            break;
                        case "初级管理员":
                            result = mangerDao.Querry(id);
                            refreshjTable(result, "初级管理员");
                            break;
                        default:
                            System.out.println("btnsearch.addActionListener：没有对应的Item！");

                    }
                    if (jTable.getRowCount() == 0) {
                        JOptionPane.showMessageDialog(jPanel, "没有搜索到记录，请确认id或手机号后重新搜索！");
                    }
                }

            }
        });
        btninsert.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                List<String> boxItem = getBoxItem();
                Result resultbtninsert = new Result();
                resultbtninsert.setStatus("1");//状态为1表示为新增
                if (boxItem.get(0).equals("1")) {
                    switch (boxItem.get(1)) {
                        case "景区":
                            new TourismAlliance(resultbtninsert);
                            break;
                        case "IC卡":
                            new IcCardManagement(resultbtninsert);
                            break;
                        case "会员":
                            new MemberRegistration(resultbtninsert);
                            break;
                        case "网点":
                            new NetworkManagement(resultbtninsert);
                            break;
                        case "初级管理员":
                            new JuniorManagement(resultbtninsert);
                            break;
                        default:
                            System.out.println("btninsert.addActionListener：没有对应的Item！");
                    }
                }
            }
        });
        btnupdate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isSearch == false) {
                    JOptionPane.showMessageDialog(jPanel, "请先搜索要修改的记录！");
                } else {
                    String id = "";
                    List<String> tableline = getTableLline();
                    id = tableline.get(1);
                    Result resultbtnupdate = new Result();
                    resultbtnupdate.setStatus("0");//状态为0表示为修改
                    resultbtnupdate.setMessage(id);//存入id
                    if (tableline.get(0).equals("1")) {
                        switch (boxItembtnupdate) {
                            case "景区":
                                new TourismAlliance(resultbtnupdate);
                                break;
                            case "IC卡":
                                new IcCardManagement(resultbtnupdate);
                                break;
                            case "会员":
                                new MemberRegistration(resultbtnupdate);
                                break;
                            case "网点":
                                new NetworkManagement(resultbtnupdate);
                                break;
                            case "初级管理员":
                                new JuniorManagement(resultbtnupdate);
                                break;
                            default:
                                System.out.println("btninsert.addActionListener：没有对应的Item！");
                        }
                    } else {
                        JOptionPane.showMessageDialog(jPanel, "请点击要修改的记录！");
                    }
                }
            }
        });
        btndelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isSearch == false) {
                    JOptionPane.showMessageDialog(jPanel, "请先搜索要删除的记录！");
                } else {
                    InterTabDao interTabDao = new InterTabDao();
                    ICcardDao iCcardDao = new ICcardDao();
                    MangerDao mangerDao = new MangerDao();
                    scTabDao scTabDao = new scTabDao();
                    vipTabDao vipTabDao = new vipTabDao();
                    List<String> tableline = getTableLline();
                    String id = tableline.get(1);
                    if (tableline.get(0).equals("1")) {
                        int r = JOptionPane.showConfirmDialog(jPanel, "将删除您选中的记录！", "确认删除？", JOptionPane.OK_CANCEL_OPTION);
                        if (r == JOptionPane.OK_OPTION) {
                            Result result = new Result();
                            switch (boxItembtnupdate) {
                                case "景区":
                                    result = scTabDao.Delete(id);
                                    break;
                                case "IC卡":
                                    result = iCcardDao.Delete(id);
                                    break;
                                case "会员":
                                    result = vipTabDao.Delete(id);
                                    break;
                                case "网点":
                                    result = interTabDao.Delete(id);
                                    break;
                                case "初级管理员":
                                    result = mangerDao.Delete(id);
                                    break;
                                default:
                                    System.out.println("btninsert.addActionListener：没有对应的Item！");
                            }
                            if (result.getStatus().equals("1")) {
                                JOptionPane.showMessageDialog(jPanel, "删除成功！");
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(jPanel, "请点击要删除的记录！");
                    }


                }
            }
        });
    }

    /**
     * 根据穿来的字符串进行查询
     * 并更新到表格中
     *
     * @param result
     */
    public void refreshjTable(Result result, String str) {
        Vector<String> vector = new Vector<>();
        Vector<Vector> datavector = new Vector<>();
        Vector datavecter2;
        vector.add("id");
        vector.add("info");
        if (result.getStatus().equals("1")) {

            switch (str) {
                case "景区":
                    List<scTab> listsc = (List<scTab>) result.getMessage();
                    for (int i = 0; i < listsc.size(); i++) {
                        datavecter2 = new Vector();
                        datavecter2.add(listsc.get(i).getScNo());
                        datavecter2.add("景区名称：" + listsc.get(i).getScName() + " 、地址：" + listsc.get(i).getScP() + "  、联系电话：" + listsc.get(i).getScTel());
                        datavector.add(datavecter2);
                    }
                    break;
                case "IC卡":
                    List<ICcard> listic = (List<ICcard>) result.getMessage();
                    for (int i = 0; i < listic.size(); i++) {
                        datavecter2 = new Vector();
                        String status = "";
                        switch (listic.get(i).getIcstatu()) {
                            case 1:
                                status = "新卡";
                                break;
                            case 2:
                                status = "已发卡";
                                break;
                            case 3:
                                status = "挂失";
                                break;
                            case 4:
                                status = "报损";
                                break;
                        }

                        datavecter2.add(listic.get(i).getIcID());
                        datavecter2.add("卡当前状态:" + status + "  、发卡时间：" + listic.get(i).getIcDate() + "  、余额：" + listic.get(i).getIDRest() + "  、发卡人：" + listic.get(i).getCardCreat());
                        datavector.add(datavecter2);
                    }

                    break;
                case "会员":
                    List<vipTab> listvip = (List<vipTab>) result.getMessage();
                    for (int i = 0; i < listvip.size(); i++) {
                        datavecter2 = new Vector();
                        datavecter2.add(listvip.get(i).getIcID());
                        datavecter2.add("会员名：" + listvip.get(i).getName() + " 、性别：" + listvip.get(i).getSex() + " 、联系电话：" + listvip.get(i).getTel());
                        datavector.add(datavecter2);
                    }
                    break;
                case "网点":
                    List<InterTab> listint = (List<InterTab>) result.getMessage();
                    for (int i = 0; i < listint.size(); i++) {
                        datavecter2 = new Vector();
                        datavecter2.add(listint.get(i).getInterID());
                        datavecter2.add("网点名称：" + listint.get(i).getInterName() + " 、网点电话：" + listint.get(i).getInterTel() + "  、网点地址：" + listint.get(i).getInterLocat());
                        datavector.add(datavecter2);
                    }
                    break;
                case "初级管理员":
                    List<Manger> listmn = (List<Manger>) result.getMessage();
                    for (int i = 0; i < listmn.size(); i++) {
                        datavecter2 = new Vector();
                        datavecter2.add(listmn.get(i).getID());
                        datavecter2.add("姓名：" + listmn.get(i).getName() + " 、联系电话：" + listmn.get(i).getAccount() + "  、所属网点编号：" + listmn.get(i).getInterID());
                        datavector.add(datavecter2);
                    }
                    break;
                default:
                    System.out.println("refreshjTable：没有对应的Item！");
            }

        }
        defaultTableModel.setDataVector(datavector, vector);

        //设置第一列列宽
        TableColumn firsetColumn = jTable.getColumnModel().getColumn(0);
        firsetColumn.setPreferredWidth(70);//默认显示的宽度
        firsetColumn.setMaxWidth(300);//最大的宽度
        firsetColumn.setMinWidth(70);//最小的宽度
        //设置第二列列宽
        TableColumn secondColumn = jTable.getColumnModel().getColumn(1);
        secondColumn.setPreferredWidth(426);//默认显示的宽度
        secondColumn.setMaxWidth(700);//最大的宽度
        secondColumn.setMinWidth(380);//最小的宽度
        //关闭表格自动调整的状态
        jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //设置JScrollPane的水平滚动条的方式
        jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        FitTableColumns(jTable);
    }


    /**
     * 获取table中要操作的行的id
     * 定义List<String> result 的变量来接收
     * result.get(0)为状态码
     * result.get(1)为数据
     *
     * @return
     */
    public List<String> getTableLline() {
        List<String> result = new ArrayList<>();
        String id = "";
        int row;
        row = jTable.getSelectedRow();
        if (row == -1) {

            result.add("-1");//获取失败
            result.add("没有选择要操作的行");
        } else {
            id = (String) jTable.getValueAt(row, 0);

            result.add("1");//获取成功
            result.add(id);
        }
        //测试
        System.out.println("getTableLline：状态->" + result.get(0));
        System.out.println("getTableLline：选择的行的id->" + result.get(1));
        return result;
    }

    /**
     * 获取下拉列表选择的item
     * 后续可以添加转换成表名的操作
     * result.get(0)为状态码
     * result.get(1)为数据
     *
     * @return
     */
    public List<String> getBoxItem() {
        List<String> result = new ArrayList<>();
        String item = jComboBox.getSelectedItem().toString().trim();
        result.add("1");//获取成功
        result.add(item);
        //测试
        System.out.println("getBoxItem：状态->" + result.get(0));
        System.out.println("getBoxItem()：下拉列表选择的item->" + result.get(1));
        return result;
    }

    /**
     * 设置列宽自适应
     * @param myTable
     */
    public void FitTableColumns(JTable myTable) {
        JTableHeader header = myTable.getTableHeader();
        int rowCount = myTable.getRowCount();
        Enumeration columns = myTable.getColumnModel().getColumns();
        while (columns.hasMoreElements()) {
            TableColumn column = (TableColumn) columns.nextElement();
            int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
            int width = (int) myTable.getTableHeader().getDefaultRenderer()
                    .getTableCellRendererComponent(myTable, column.getIdentifier()
                            , false, false, -1, col).getPreferredSize().getWidth();
            for (int row = 0; row < rowCount; row++) {
                int preferedWidth = (int) myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable,
                        myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
                width = Math.max(width, preferedWidth);
            }
            header.setResizingColumn(column); // 此行很重要
            column.setWidth(width + myTable.getIntercellSpacing().width);
        }
    }

    public static void main(String[] args) {
        Result result = new Result();
        new AdminiView(result);
    }
}
